package com.xhwl.centiotdata.handler.alarm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.handler.alarm.impl.AlarmHuaWeiIotDAVideoSurveillanceEventHandler;
import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.service.cent.ICentAlarmService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.utils.SpringContextUtils;
import com.xhwl.common.constant.cent.IOTReceiveConstant;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.alarm.iot.IotAlarmBody;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.device.iot.IotDeviceJson;
import com.xhwl.common.dto.cent.device.iot.NotifyData;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.alarm.AlarmLog;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author Leon
 * @Description: TODO
 * @Date: 2022/3/22 15:40
 */
@Slf4j
public abstract class AlarmHandler implements InitializingBean {

    @Autowired
    public IDeviceCentService deviceCentService;

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    public ICentAlarmService centAlarmService;

    @Autowired
    public GeneralProducer generalProducer;


    /*
    JSON text NotifyData
     */
    public List<IotAlarmBody> analysisHuaWeiIotDABody(String jsonText) {
        JSONObject body = JSONObject.parseObject(jsonText);
        return JSONArray.parseArray(body.get(IOTReceiveConstant.SERVICES).toString(), IotAlarmBody.class);
    }

    public NotifyData analysisHuaWeiIotDANotifyData(String jsonText) {
        //log.info("华为IOTDA推送原始数据为=================》{}", jsonText);
        IotDeviceJson iotDeviceJson = JSONObject.parseObject(jsonText, IotDeviceJson.class);
        return iotDeviceJson.getNotify_data();
    }

    public void pushHuaWeiIotDAIotAlarmBody(IotAlarmBody iotAlarmBody, DeviceDTO device) {
        throw new UnsupportedOperationException();
    }

    public void execute(String jsonText) {
        NotifyData notifyData = analysisHuaWeiIotDANotifyData(jsonText);
        List<IotAlarmBody> services = analysisHuaWeiIotDABody(notifyData.getBody().toString());
        for (int i = 0; i < services.size(); i++) {
            IotAlarmBody iotAlarmBody = services.get(i);
            AlarmLog alarmLog = new AlarmLog();
            alarmLog.setTag(iotAlarmBody.getService_id());
            alarmLog.setContent(JSONObject.toJSONString(iotAlarmBody));
            alarmLog.setPushTime(new Date());
            centAlarmService.insert(alarmLog);
            AlarmHandler invokeStrategy = AlarmFactory.getInvokeStrategy(iotAlarmBody.getService_id());
            if (Objects.nonNull(invokeStrategy)) {
                DeviceDTO device = getDevice(notifyData.getHeader().getDevice_id());
                if (Objects.isNull(device)) {
                    continue;
                }
                invokeStrategy.pushHuaWeiIotDAIotAlarmBody(iotAlarmBody, device);
//                log.info("加工解析数据为============》{}，设备对象为============》{},======>beanName{}",
//                        JSONObject.toJSONString(iotAlarmBody),
//                        JSONObject.toJSONString(device),iotAlarmBody.getService_id());
            }
        }
    }

    public DeviceDTO getDevice(String iotDeviceId) {
        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setIotDeviceId(iotDeviceId);
        Page<DeviceDTO> deviceDTOPage = deviceCentService.pageDevice(null, devicePageQuery);
        return Optional.ofNullable(deviceDTOPage).map(Page::getRecords)
                .filter(item -> CollectionUtils.isNotEmpty(item))
                .map(item -> item.get(0)).orElse(null);
    }

    public <T> void sendMq(String topic, T text) {
        generalProducer.send(topic, text);
    }

    public <T> T parseObject(String text, Class<T> clazz) {
        try {
            T t = JSONObject.parseObject(text, clazz);
            return t;
        } catch (Exception e) {
            log.error("=============================>JSON格式解析异常，Exception：{}", e.getMessage());
        }
        return null;
    }

}
